package csc.daonjpa.java.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.Transaction;

@Service
public class TransactionDAOImpl implements TransactionDAO {

	@PersistenceContext
	private EntityManager entityManager;
	
	@Transactional
	public boolean addTransaction(Transaction transaction) {
		entityManager.persist(transaction);
		return true;
	}

	@Transactional
	public List<Transaction> getTransactions() {
		List<Transaction> transactions = null;
		TypedQuery<Transaction> query = entityManager.createQuery("Select a from Transaction a", Transaction.class);
		transactions = query.getResultList();
		return transactions;
	}

	@Transactional
	public List<Transaction> getTransactionsSource(String loginId) {
		List<Transaction> transactions = null;
		TypedQuery<Transaction> query = entityManager.createQuery("Select a from Transaction a Where a.loginIdSource = :lg", Transaction.class);
		query.setParameter("lg", loginId);
		transactions = query.getResultList();
		return transactions;
	}

	@Transactional
	public List<Transaction> getTransactionsTarget(String loginId) {
		List<Transaction> transactions = null;
		TypedQuery<Transaction> query = entityManager.createQuery("Select a from Transaction a Where a.loginIdTarget = :lg", Transaction.class);
		query.setParameter("lg", loginId);
		transactions = query.getResultList();
		return transactions;
	}

	@Transactional
	public List<Transaction> searchByDate(Date fromDate, Date toDate) {
		List<Transaction> transactions = null;
		TypedQuery<Transaction> query = entityManager.createQuery("Select a from Transaction a Where a.date Between :start And :end", Transaction.class);
		query.setParameter("start", fromDate);
		query.setParameter("end", toDate);
		transactions = query.getResultList();
		return transactions;
	}

}
